package com.example.hibernate.program;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class Driver {

	public static void main(String[] args) {
		// createEmployee();
		// Employee employee = readEmployee();
		// System.out.println(employee);
		// deleteEmployee();
		updateEmployee();
	}

	public static void updateEmployee() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		try {
			Employee employee = (Employee) session.get(Employee.class, 40L);
			System.out.println(employee);
			employee.setFirstName("Demba Ba");
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
		}
		session.close();
		sessionFactory.close();
	}

	public static void deleteEmployee() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		try {
			Employee employee = (Employee) session.get(Employee.class, 38L);
			session.delete(employee);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
		}
		session.close();
		sessionFactory.close();
	}

	public static Employee readEmployee() {
		Employee employee = null;
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		try {
			employee = (Employee) session.get(Employee.class, 15L);
		} catch (Exception e) {
			transaction.rollback();
		}
		session.close();
		sessionFactory.close();
		return employee;
	}

	public static void createEmployee() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		try {
			{
				Employee employee = new Employee();
				employee.setFirstName("Önder");
				employee.setLastName("ŞAHİN");
				employee.setEmail("crazyboy@gmail.com");
				session.save(employee);
			}
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
		}
		session.close();
		sessionFactory.close();

	}
}
